package com.saui.traceu;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import com.saui.traceu.model.Session;
import com.saui.traceu.model.TraceDBAdapter;

public class TraceList extends ListActivity{
	
    private Button showButton;
    private ListView lv;
    protected static final int RENAME_DIALOG = 50;
    int currPosition;
    private Context ctx;
    Session curSession;
    //variable for saving Positions and IDs checked
    long[] curCheckedIds;
    ArrayList<Boolean> curCheckListPos;
    
    private TraceDBAdapter dbAdapter;
    private Cursor theCursor;    
    private SimpleCursorAdapter listCursorAdapter;
    
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.layout_list);
    	registerForContextMenu(getListView());
    	//lv = this.getListView();
    	lv = (ListView) findViewById(android.R.id.list);
    	
    	//setup and open database
        dbAdapter = new TraceDBAdapter(this);
        dbAdapter.open();
        ctx = this.getApplicationContext();
        curSession = new Session();
        curCheckListPos = new ArrayList<Boolean>();
               
    	//Populate listView with data from the database.
    	populateListView();
    	
    	// set up the button to show traces
     	showButton = (Button) findViewById(R.id.button_show);
    	showButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View view) {
				long[] ids = lv.getCheckedItemIds();	
				
				
				if(ids.length !=0){
	        		//Display delete confirmation dialog
					Intent i = new Intent(ctx, TraceMapHistory.class);
			        i.putExtra("sessionIDs", ids);			     
			        startActivity(i);
				}
				else{
					//Display no items selected dialog
	        		Dialog d = onCreateDialog(2);
	        		d.show();
				}
			}	
    	}); 
    	
    	/** 
    	 * set up the dialog for editing title and saving
    	 */
    	lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {

            	Dialog d = new Dialog(lv.getContext());
				Window w = d.getWindow();
				w.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, 
						WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
				d.setTitle("Rename Trace");
				d.setContentView(R.layout.layout_list_dialog);
		
				//set text edit text for trace name
				EditText traceNameEditText;
                traceNameEditText = (EditText)d.findViewById(R.id.list_session_name);
				
				 //got to cursor position to populate class session variable
				theCursor.moveToPosition(position);
				
				//place all information into class Session variable -- easier for saving
				// info while in save button
				curSession.setTitle(theCursor.getString(theCursor.getColumnIndexOrThrow(TraceDBAdapter.KEY_SESSION_TITLE)));
				curSession.setId(id);
				curSession.setSaved(true);
				curSession.setEndTime(theCursor.getLong(theCursor.getColumnIndexOrThrow(TraceDBAdapter.KEY_SESSION_ENDTIME)));
				curSession.setStartTime(theCursor.getLong(theCursor.getColumnIndexOrThrow(TraceDBAdapter.KEY_SESSION_STARTTIME)));

				//put the current name into the window to allow for editing
				traceNameEditText.setText(curSession.getTitle());
				
				// setUp save button
				saveButtonHelper(d);
		
				// setUp continue button
				cancelButtonHelper(d);
				
				d.show();

            	return true;
            }
    	});
    
    	
    	//save state every time item is checked
    	lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
            	//save checked positions and IDs for state
            	curCheckedIds=lv.getCheckedItemIds();
            	saveCurCheckedPosBool();
            }		
    	});
    }// end of onCreate
    
     
    /**
     * set on click listener to save button for the editing/saving dialog passed as argument
     */
    private void saveButtonHelper(final Dialog d) {
    	final Dialog newD = d;
		Button saveButton = (Button)d.findViewById(R.id.list_save_button);
		saveButton.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v) {
				final EditText nameText = (EditText)newD.findViewById(R.id.list_session_name);

				curSession.setTitle(nameText.getText().toString());				
				dbAdapter.updateSession(curSession);
				
				newD.dismiss();
			
				//requery and populate
				saveCurCheckedPosBool();
				theCursor.requery();
				//populateListView();
				//reCheckSessions();
			}
		});
	}
    
    
    /**
     * set on click listener to cancel button for the editing/daving dialog passed as argument
     */
    private void cancelButtonHelper(final Dialog d) {
		Button cancelButton = (Button)d.findViewById(R.id.list_cancel);
		cancelButton.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v) {
				d.dismiss();
			}
		});
	}
    
    
    
    /**
     * function called to populate the list view
     * makes db call and puts cursor into class variable
     * 
     */
    public void populateListView(){
    	//get all of the sessions into a cursor
    	theCursor = dbAdapter.getAllSessions();
    	startManagingCursor(theCursor);
    	
    	//create simple adapter to bind to the list    	
    	listCursorAdapter = new SimpleCursorAdapter(
    				this,
    	            //android.R.layout.simple_list_item_checked, // Use a template that displays a text view
    	            android.R.layout.simple_list_item_multiple_choice,
    	            theCursor, // Give the cursor to the list adapter
    	            
    	            new String[] {TraceDBAdapter.KEY_SESSION_TITLE}, // Map the KEY_SESSION_TITLE column in the session table to...
    	            new int[] {android.R.id.text1}); // The "text1" view defined in the XML template   			
    	
    	//Set the adapter to the list
    	this.setListAdapter(listCursorAdapter);
    	lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    	lv.isLongClickable();    	    	
    }
    
    
    
    /**
	 * Populate the options for the "Menu" button
	 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	 MenuInflater inflater = getMenuInflater();
    	 inflater.inflate(R.menu.menu_list, menu);
    	 return true;
    }
    
    
    
    /**
	 * handle option menu events.
	 * 
	 */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	// Handle item selection
    	int itemnum = item.getItemId();
    	
        switch (itemnum) {
        
        case R.id.delete_item:
        	//Create and show the dialog
        	
        	//See how many items are selected.       	       	
        	if(lv.getCheckedItemIds().length !=0){
        		//Display delete confirmation dialog
        		Dialog d =onCreateDialog(1);
            	d.show();
        	}else{
        		//Display no items selected dialog
        		Dialog d = onCreateDialog(2);
        		d.show();
        	}
            return true;
            
        case R.id.select_all:
        	for(int i=0; i < lv.getCount(); i++){
        		//CheckedTextView textView = (CheckedTextView)lv.getChildAt(i);
            	//textView.setChecked(true);  
            	lv.setItemChecked(i, true);    
            	
        	}   
		    return true;
		    
        case R.id.deselect_all:
        	for(int i=0; i < lv.getCount(); i++){
        		//CheckedTextView textView = (CheckedTextView)lv.getChildAt(i);
            	//textView.setChecked(false);       		
            	lv.setItemChecked(i, false);
            	
        	}
        	return true;
        	
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    
    
    /**
	 *  Alert Dialog box for delete Menu item
	 *  
	 */
    protected Dialog onCreateDialog(int id) {
    	Dialog d = null;
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	switch(id){
	    	case 1:
			builder.setMessage("Are you sure you want to delete the selected traces?")
			       .setCancelable(false)
			       .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        
			        	   long[] selectedItems  = lv.getCheckedItemIds();	
			        	   
			        	   dbAdapter.deleteSessions(selectedItems);
			        	   populateListView();
	
			           }
			       })
			       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });	
					d = (Dialog) builder.create();
			break;
			
	    	case 2:
	    		builder.setMessage("No traces selected");
	    		d = builder.create();
	    	break;
	    	
	    	case TraceList.RENAME_DIALOG:
				d = new Dialog(this);
				Window w = d.getWindow();
				w.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, 
						WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
				d.setTitle("Rename Trace");
				d.setContentView(R.layout.layout_list_dialog);
		
				//set text edit text for trace name
				EditText traceNameEditText;
				traceNameEditText = (EditText)d.findViewById(R.id.list_session_name);
				theCursor.moveToPosition( (int) lv.getSelectedItemId());
				
				String x = theCursor.getString(theCursor.getColumnIndexOrThrow(TraceDBAdapter.KEY_SESSION_TITLE));
				traceNameEditText.setText(x + " TEST");
				
			break;
	    	//************************
		}
    	return d;
    }
    

    public void printTester(String text){
		Toast.makeText(this,text,Toast.LENGTH_LONG).show();
		
	}
    
    /**
     * Set the checkboxes to checked or not according to the values 
     * saved on the curCheckListPos ArrayList
     * */
    public void reCheckSessions(){
    	
    	//cycle through the saved positions
    	for (int i=0; i < curCheckListPos.size()   ;i++){
    		//put the list item at the same state it was at before	
    		lv.setItemChecked(i, curCheckListPos.get(i));
    
    	}
    }

    /**
     * Checks what items of the listview are checked and which are not
     * */
    private void saveCurCheckedPosBool(){
    	
    	boolean result;
    	//clear the list to make sure all values are true
    	curCheckListPos.clear(); 	
    	//go through all items in list 
    	for (int i=0; i < lv.getCount();i++){ 			
    			result = lv.isItemChecked(i);
    			curCheckListPos.add(result);
    	}
    }

}
